package com.framework.modules.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.live.TencentLiveKit;
import com.framework.common.utils.QuickHelper;
import com.framework.common.utils.R;
import com.framework.modules.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 系统日志
 */
@Controller
@RequestMapping("/sdk/config")
@Api(tags = "SDK设置")
public class SysSdkController {

	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/zhibo")
	@RequiresPermissions("sdk:config:zhibo")
	@ApiOperation(value="直播配置")
	public R zhibo(String method,String active,String data) {
		String key = "zhibo.sdk.config";
		if ("save".equals(method)) {
			JSONObject obj = QuickHelper.json2object(data, JSONObject.class);
			JSONObject activeConfig = obj.getJSONObject("templateConfig").getJSONObject(active);
			String templateId = activeConfig.getString("TemplateId");

			sysConfigService.updateValueByKey(key, data);

			Map<String, String> attrs = new HashMap<>();

			Iterator it = activeConfig.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
				String name = entry.getKey();
				Object value = entry.getValue();
				attrs.put(name, value == null ? "" : value.toString());
			}

			TencentLiveKit.updateTencentLiveNotifyTemplate(Long.valueOf(templateId), attrs, obj.getString("secretId"), obj.getString("secretKey"));

			return R.ok("保存成功").put("ref", activeConfig);
		} else {
			String value = sysConfigService.getValue(key);
			JSONObject obj = QuickHelper.json2object(value, JSONObject.class);
			return R.ok("获取成功").put("data", obj);
		}
	}

}
